package com.onec.service.auth.service;

import com.onec.service.api.content.PatternUtil;
import com.onec.service.api.enums.StatusEnum;
import com.onec.service.auth.dao.CustomerPermissionRepository;
import com.onec.service.auth.dao.CustomerRepository;
import com.onec.service.auth.dao.PermissionRepository;
import com.onec.service.auth.dto.CustomerDto;
import com.onec.service.auth.entity.CustomerInfo;
import com.onec.service.auth.entity.CustomerPermission;
import com.onec.service.auth.entity.PermissionInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;

/**
 * @author ONEC
 * 用户注册登录控制
 */
@Slf4j
@Service
public class CustomerUserServiceImpl implements UserDetailsService {

    @Autowired
    private CustomerRepository customerRepository;
    @Resource
    private PermissionRepository permissionRepository;
    @Resource
    private CustomerPermissionRepository customerPermissionRepository;

    @Override
    public UserDetails loadUserByUsername(String param) throws UsernameNotFoundException {

        log.info("认证服务：进行访问认证：{}", param);
        CustomerInfo customer;
        if (param.matches(PatternUtil.EMAIL)) {
            customer = customerRepository.findByEmail(param);
        } else {
            customer = customerRepository.findByPhone(param);
        }
        if (Optional.ofNullable(customer).isEmpty()) {
            log.info("暂未发现用户：跳转到注册页面：{}", param);
            throw new UsernameNotFoundException("该用户尚未注册");
        }
        // 用户名不存在：用户已经锁定
        if (StatusEnum.FREEZE.equals(customer.getStatus())) {
            log.info("该用户已经锁定：跳转页面：{}", param);
            throw new LockedException("用户已锁定");
        }
        Collection<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
        List<CustomerPermission> customerPermissions = customerPermissionRepository.findByCustomerId(customer.getId());
        if (!customerPermissions.isEmpty()) {
            for (CustomerPermission customerPermission : customerPermissions) {
                Optional<PermissionInfo> permission = permissionRepository.findById(customerPermission.getPermissionId());
                permission.ifPresent(permissionInfo -> simpleGrantedAuthorities.add(new SimpleGrantedAuthority(permissionInfo.getName())));
            }
        }
        log.info("认证服务：访问信息配置完成进行认证：{}", param);
        return new CustomerDto(customer, simpleGrantedAuthorities);
    }
}
